package com.shangdiao.sd_server.server.controller;

import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.shangdiao.sd_server.constant.Constant;
import com.shangdiao.sd_server.constant.ErrorCode;
import com.shangdiao.sd_server.generator.pojo.SdAdmin;
import com.shangdiao.sd_server.generator.pojo.SdAdminExample;
import com.shangdiao.sd_server.pojo.ResponseMsg;
import com.shangdiao.sd_server.service.AdminService;
import com.shangdiao.sd_server.service.RedisService;
import com.shangdiao.sd_server.util.MD5Util;
import com.shangdiao.sd_server.util.RequestUtil;

@Controller
@RequestMapping("/open/server")
public class ServerLoginController {

	@Autowired
	RedisService redisService;
	@Autowired
	AdminService adminService;

	@RequestMapping(value = { "/login.json" })
	@ResponseBody
	@Transactional
	public ResponseMsg selectCompany(HttpServletRequest request,
			HttpServletResponse response) {

		try {
			String userName = RequestUtil.get(request, "userName");
			String pwd = RequestUtil.get(request, "pwd");
			SdAdminExample example = new SdAdminExample();
			example.or().andAdminNameEqualTo(userName)
				.andAdminPwdEqualTo(MD5Util.encodeByMD5(pwd));
			List<SdAdmin> admin_list = adminService.selectAdmin(example);
			if(admin_list.size() > 0){
				Random random = new Random();
				Integer uid = random.nextInt(10);
				String token = MD5Util.encodeByMD5(Constant.SERVER_TOKEN_PRE + uid + System.currentTimeMillis());
				redisService.set(Constant.SERVER_TOKEN_PRE, token, 60 * 100);
				return new ResponseMsg("登录成功", ErrorCode.OK, null);
			}
			return new ResponseMsg("登录失败", ErrorCode.ERROR, null);
		} catch (Exception e) {
			e.printStackTrace();
			return new ResponseMsg("服务器出错", ErrorCode.SERVER_ERROR, null);
		}
	}

}
